package api

import (
	"errors"
	
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"

	"collecter/app/common/enum"
	"collecter/app/common/helper"
	"collecter/app/common/service"
	"collecter/app/controller"
	"collecter/app/model"
)

type CategoryController struct {
	controller.BaseController
}

func (c *CategoryController) List(ctx *gin.Context) {
	var user model.Users
	if val, err := c.GetUserInfo(); err != nil {
		c.FormatReturn(enum.FAILED, "", err.Error())
	} else {
		user = *val
	}
	category := service.NewCategory(user.Id)
	if tree, err := category.TreeList(); err != nil {
		c.FormatReturn(enum.FAILED, "", err.Error())
	} else {
		c.FormatReturn(enum.SUCCESS, tree)
	}
}

// Create
//
//	@Description: 新增或者更新分类
//	@receiver c
//	@param ctx
func (c *CategoryController) Create(ctx *gin.Context) {
	type inType struct {
		Id       int64  `json:"id,omitempty"`
		Pid      int64  `json:"pid,omitempty"`
		CateName string `json:"cateName,omitempty"`
		Icon     string `json:"icon,omitempty"`
		Sort     int    `json:"sort,omitempty"`
	}
	var inData inType
	if err := controller.Ctx.BindJSON(&inData); err != nil {
		c.FormatReturn(enum.FAILED, "", err.Error())
	}
	if len(inData.CateName) == 0 || len(inData.CateName) > 255 || len(inData.Icon) > 255 {
		c.FormatReturn(6, "")
	}
	var user model.Users
	if val, err := c.GetUserInfo(); err != nil {
		c.FormatReturn(enum.FAILED, "", err.Error())
	} else {
		user = *val
	}
	category := service.NewCategory(user.Id)
	category.Sort = inData.Sort
	category.CateName = inData.CateName
	category.Icon = inData.Icon
	category.Pid = inData.Pid
	if inData.Id > 0 {
		// update
		if err := category.Update(inData.Id); err != nil {
			c.FormatReturn(enum.FAILED, "", err.Error())
		}
	} else {
		// create
		if err := category.Create(); err != nil {
			c.FormatReturn(enum.FAILED, "", err.Error())
		}
	}

	c.FormatReturn(enum.SUCCESS, "")
}

func (c *CategoryController) Delete(ctx *gin.Context) {
	type inType struct {
		Id int64 `json:"id,omitempty"`
	}
	var inData inType
	if err := controller.Ctx.BindJSON(&inData); err != nil {
		c.FormatReturn(enum.FAILED, "", err.Error())
	}
	if inData.Id == 0 {
		c.FormatReturn(6, "")
	}
	var category model.Categorys
	if err := helper.Db.Where("id = ?", inData.Id).First(&category).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			c.FormatReturn(enum.FAILED, "", "分类不存在")
		}
		c.FormatReturn(enum.FAILED, "", err.Error())
	}
	if err := helper.Db.Delete(&category).Error; err != nil {
		c.FormatReturn(enum.FAILED, "", err.Error())
	}
	c.FormatReturn(enum.SUCCESS, "")
}
